package ifgi.potwc.ipt.json;

import ifgi.potwc.ipt.database.IptDatabase;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * This class handles the creation of JSON messages for making requests at Cosm.
 * 
 * @author saschak.
 */
public class IptJSONManager
{
    // Database
    private IptDatabase iptDb;
    private SQLiteDatabase db;

    /**
     * Constructor.
     * 
     * @param _context
     */
    public IptJSONManager(Context _context)
    {
	iptDb = new IptDatabase(_context);
	db = iptDb.getWritableDatabase();
    }

    /**
     * Returns a JSON object for the given datastream needed for the HTTP
     * request at Cosm. The object contains a collection of datapoints. Each
     * datapoint contains and a value from the database that has not been
     * uploaded yet, and the timestamp at which the value was measured. Example:
     * "{"datapoints":[{"at":the_timestamp,"value":the_value}, ...]}"
     * 
     * @param _datastream
     * @return The JSON object for HTTP request containing the datapoints
     * @throws JSONException
     */
    public String createJsonMessage(String _datastream) throws JSONException
    {
	// Message for cosm request
	String message = "";

	// The SQL query
	String sqlQuery = "SELECT timestamp, " + _datastream + " FROM "
		+ _datastream + IptDatabase.TABLE_TAG + " WHERE "
		+ IptDatabase.UPLOADED + " = 0";

	// Cursor for reading the query result
	Cursor result = null;

	// List of JSONObjects; each JSONObject represents one row of the SQL
	// query result table
	JSONArray list = new JSONArray();

	try
	{
	    // Make the SQL query
	    result = db.rawQuery(sqlQuery, null);

	    // Read each row from the query result
	    while (result.moveToNext())
	    {
		// Create a new JSONObject for the row
		JSONObject obj = new JSONObject();
		obj.put("value", result.getDouble(1));
		obj.put("at", result.getString(0));

		// Put the JSONObject to the list
		list.put(obj);
	    }

	    // Create the outer JSONObject that represents the whole message
	    JSONObject jsonMessage = new JSONObject();
	    jsonMessage.put("datapoints", list);

	    // Turn the message into a String
	    message = jsonMessage.toString();
	}
	finally
	{
	    // Close cursor
	    result.close();
	}

	return message;
    }
}